package com.screen.screendisplay.service.impl.coal;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.screen.screendisplay.entity.coal.CoalOpermonRtOutput;
import com.screen.screendisplay.mapper.coal.CoalOpermonRtOutputMapper;
import com.screen.screendisplay.service.coal.CoalOpermonRtOutputService;
import com.screen.screendisplay.vo.coal.CoalProductionOutputVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 * 运行检测产出情况表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class CoalOpermonRtOutputServiceImpl extends ServiceImpl<CoalOpermonRtOutputMapper, CoalOpermonRtOutput> implements CoalOpermonRtOutputService {

    @Override
    public List<CoalProductionOutputVO> getProductionOutput(Integer year) {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        
        // 计算6个月前的日期
        LocalDate sixMonthsAgo = currentDate.minusMonths(5);
        
        // 查询最近6个月的数据
        LambdaQueryWrapper<CoalOpermonRtOutput> wrapper = Wrappers.lambdaQuery();
        wrapper.ge(CoalOpermonRtOutput::getYear, sixMonthsAgo.getYear())
               .orderByDesc(CoalOpermonRtOutput::getYear)
               .orderByDesc(CoalOpermonRtOutput::getMonth);
        
        List<CoalOpermonRtOutput> outputList = this.list(wrapper);
        
        // 按年月分组取最新数据
        Map<String, CoalOpermonRtOutput> monthlyDataMap = new HashMap<>();
        
        for (CoalOpermonRtOutput output : outputList) {
            String yearMonth = output.getYear() + "-" + output.getMonth();
            // 只保留每个月的第一条记录（因为已按年月降序排序）
            if (!monthlyDataMap.containsKey(yearMonth)) {
                monthlyDataMap.put(yearMonth, output);
            }
        }
        
        // 转换为VO列表
        List<CoalProductionOutputVO> resultList = new ArrayList<>();
        
        // 生成最近6个月的数据
        for (int i = 0; i < 6; i++) {
            LocalDate monthDate = currentDate.minusMonths(i);
            String yearMonth = monthDate.getYear() + "-" + monthDate.getMonthValue();
            
            CoalProductionOutputVO vo = new CoalProductionOutputVO();
            vo.setYear(monthDate.getYear());
            vo.setMonth(monthDate.getMonthValue());
            
            CoalOpermonRtOutput output = monthlyDataMap.get(yearMonth);
            if (output != null) {
                vo.setRealtimeOutput(output.getRealtimeOutput());
                vo.setRealtimeStock(output.getRealtimeStock());
            }
            
            resultList.add(vo);
        }
        
        return resultList;
    }
}
